from django.http import JsonResponse
from django.shortcuts import HttpResponse

from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework import permissions, status

from rest_framework.settings import api_settings
from rest_framework.utils import json
from rest_framework_mongoengine import viewsets

from mongoengine import QuerySet

from authorshow.models.models import StandardResultSetPagination
from authorshow.models.utils import create_coll_id
from conference.models import Statistics, Meetings, Subjects
from conference.serializer import StatisticsSerializer, MeetingsSerializer, SubjectsSerializer
from conference.utils import select_meeting, select_subject


def perform_create(self, serializer):
    serializer.save()

def perform_update(self, serializer):
    serializer.save()

def get_success_headers(self, data):
    try:
        return {'Location': str(data[api_settings.URL_FIELD_NAME])}
    except (TypeError, KeyError):
        return {}

class StatisticsViewSet(viewsets.ModelViewSet):
    serializer_class = StatisticsSerializer
    queryset: QuerySet = Statistics.objects.all()

    # 用于分页
    pagination_class = StandardResultSetPagination
    # 权限控制
    permission_classes = (
        permissions.IsAuthenticatedOrReadOnly,
    )

    # 下述是创建方法,用于新生成一个新的id号
    def create(self, request, *args, **kwargs):
        data = request.data

        data['id'] = str(create_coll_id(queryset=self.get_queryset()))
        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(data=serializer.data, status=status.HTTP_201_CREATED, headers=headers)

class MeetingsViewSet(viewsets.ModelViewSet):
    serializer_class = MeetingsSerializer
    queryset: QuerySet = Meetings.objects.all()

    # 用于分页
    pagination_class = StandardResultSetPagination
    # 权限控制
    permission_classes = (
        permissions.IsAuthenticatedOrReadOnly,
    )

    def create(self, request, *args, **kwargs):
        data = request.data
        data['id'] = str(create_coll_id(queryset=self.get_queryset()))
        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(data=serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    def list(self, request, *args, **kwargs):
        '''用于会议的完整展示(包含主题报告)与根据会议进行筛选结果的展示'''
        params = request.query_params
        meeting = params.get(key='meeting')
        info = params.get(key='info')
        # 如果没有查询参数，列表全部数据
        if not (meeting or info):
            queryset = self.filter_queryset(self.get_queryset())
            page = self.paginate_queryset(queryset=queryset)
            serializer = MeetingsSerializer(instance=page, many=True)
            return self.get_paginated_response(serializer.data)
        # 有查询参数
        r_result = select_meeting(queryset=self.queryset, meeting=meeting, info=info)
        # 未查询到结果
        if r_result is None or r_result.count() is 0:
            err_msg = "未查询到结果"
            return Response(data=err_msg, status=status.HTTP_404_NOT_FOUND)
        page = self.paginate_queryset(queryset=r_result)
        # 序列化所有字段
        serializer = MeetingsSerializer(instance=page, many=True)
        # serializer = ThemeMeetingSerializer(instance=page, many=True)
        return self.get_paginated_response(serializer.data)

def meeting_keywords(request):
    '''对应url：http://localhost:8000/meeting_keywords/?id=XXX'''
    '''单一会议对应的主题报告关键词统计'''
    # 需改进？？？
    id = request.GET.get('id', None)
    if id == None:
        return HttpResponse('请提供会议 id 参数。')
    meeting = Meetings.objects.filter(id=id)[0]
    keywords = []
    length = len(meeting.themes)
    for i in range(length):
        keywords.append(meeting.themes[i].keywords)
    meeting_keywords = {}
    for i in keywords:
        if i in meeting_keywords:
            meeting_keywords[i] += 1
        else:
            meeting_keywords[i] = 1
    # return JsonResponse(meeting_keywords, json_dumps_params={'ensure_ascii': False})
    res = json.dumps(meeting_keywords, indent=4, ensure_ascii=False)
    return HttpResponse(res, content_type='application/json', charset='utf-8')


def meeting_orgs(request):
    '''对应url：http://localhost:8000/meeting_orgs/?id=XXX'''
    '''单一会议对应的主题报告机构统计'''
    id = request.GET.get('id', None)
    if id == None:
        return HttpResponse('请提供会议id参数。')
    meeting = Meetings.objects.filter(id=id)[0]
    orgs = []
    length = len(meeting.themes)
    for i in range(length):
        orgs.append(meeting.themes[i].org)
    meeting_orgs = {}
    for i in orgs:
        if i in meeting_orgs:
            meeting_orgs[i] += 1
        else:
            meeting_orgs[i] = 1
    # return JsonResponse(meeting_orgs, json_dumps_params={'ensure_ascii': False})
    res = json.dumps(meeting_orgs, indent=4, ensure_ascii=False)
    return HttpResponse(res, content_type='application/json', charset='utf-8')

class SubjectsViewSet(viewsets.ModelViewSet):
    serializer_class = SubjectsSerializer
    queryset: QuerySet = Subjects.objects.all()

    pagination_class = StandardResultSetPagination
    # 权限控制
    permission_classes = (
        permissions.IsAuthenticatedOrReadOnly,
    )

    def create(self, request, *args, **kwargs):
        data = request.data
        data['id'] = str(create_coll_id(queryset=self.get_queryset()))
        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(data=serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    def list(self, request, *args, **kwargs):
        '''主题报告的展示'''
        params = request.query_params
        meeting = params.get(key='meeting')
        report = params.get(key='report')
        keywords = params.get(key='keywords')
        org = params.get(key='org')
        speaker = params.get(key='speaker')
        # 如果没有查询参数，列表全部数据
        if not (meeting or report or keywords or org or speaker):
            queryset = self.filter_queryset(self.get_queryset())
            page = self.paginate_queryset(queryset=queryset)
            serializer = SubjectsSerializer(instance=page, many=True)
            return self.get_paginated_response(serializer.data)
        # 有查询参数
        r_result = select_subject(queryset=self.queryset, meeting=meeting, report=report, keywords=keywords, org=org, speaker=speaker)
        # 未查询到结果
        if r_result is None or r_result.count() is 0:
            err_msg = "未查询到结果"
            return Response(data=err_msg, status=status.HTTP_404_NOT_FOUND)
        page = self.paginate_queryset(queryset=r_result)
        # 序列化所有字段
        serializer = SubjectsSerializer(instance=page, many=True)
        return self.get_paginated_response(serializer.data)


def meetings_statistics(request):
    '''会议按月份分布图'''
    mapping = {}
    list = []
    for document in Statistics.objects():
        list.append(document['month'])
    unilist = set(list)
    for mon in unilist:
        mapping[mon] = []
        for document in Statistics.objects():
            if document['month'] == mon:
                mapping[mon].append(document.meeting)
    # return JsonResponse(mapping, json_dumps_params={'ensure_ascii': False})
    res = json.dumps(mapping, indent=4, ensure_ascii=False)
    return HttpResponse(res, content_type='application/json', charset='utf-8')

def keywords_statistics(request):
    '''主题报告热点图'''
    hotspot = {}
    keys = []

    for document in Subjects.objects():
        keys.append(document.keywords)
    # key = set(keys)
    for i in keys:
        if i in hotspot:
            hotspot[i] += 1
        else:
            hotspot[i] = 1
    # return JsonResponse(hotspot, json_dumps_params={'ensure_ascii': False})
    res = json.dumps(hotspot, indent=4, ensure_ascii=False)
    return HttpResponse(res, content_type='application/json', charset='utf-8')
# def meeting_keywords_statistics(request):
#     '''各个会议对应的主题报告热点图'''
#
#     meeting_keywords = {}
#     meetings = []
#     kkk = []
#     # 会议唯一值
#     for document in Subjects.objects():
#         meetings.append(document.meeting)
#     kkk = list(set(meetings))
#     # 获取会议唯一值对应的keywords列表
#     for name in kkk:
#         meeting_keywords[name] = []
#         for document in Subjects.objects():
#             if document.meeting == name:
#                 meeting_keywords[name].append(document.keywords)
#     result = {}
#     for key in meeting_keywords:
#         result[key] = {}
#         for i in meeting_keywords[key]:
#             if i in result[key]:
#                 result[key][i] += 1
#             else:
#                 result[key][i] = 1
#     return JsonResponse(result, json_dumps_params={'ensure_ascii': False})

# def meeting_org_statistics(request):
#     '''各个会议对应的机构分布图, 针对的是所有的会议，需求方面要求根据不同的会议进行统计，修改见meeting_keywords'''
#
#     meeting_keywords = {}
#     meetings = []
#     kkk = []
#     # 会议唯一值
#     for document in Subjects.objects():
#         meetings.append(document.meeting)
#     kkk = list(set(meetings))
#     # 获取会议唯一值对应的keywords列表
#     for name in kkk:
#         meeting_keywords[name] = []
#         for document in Subjects.objects():
#             if document.meeting == name:
#                 meeting_keywords[name].append(document.org)
#     result = {}
#     for key in meeting_keywords:
#         result[key] = {}
#         for i in meeting_keywords[key]:
#             if i in result[key]:
#                 result[key][i] += 1
#             else:
#                 result[key][i] = 1
#     return JsonResponse(result, json_dumps_params={'ensure_ascii': False})
